package cn.turboinfo.fuyang.api.domain.admin.usecase.product;

import cn.turboinfo.fuyang.api.domain.common.service.company.HousekeepingCompanyService;
import cn.turboinfo.fuyang.api.domain.common.service.product.ProductService;
import cn.turboinfo.fuyang.api.domain.common.service.product.ProductSkuService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.enumeration.product.ProductSkuStatus;
import cn.turboinfo.fuyang.api.entity.common.enumeration.product.ProductStatus;
import cn.turboinfo.fuyang.api.entity.common.pojo.product.Product;
import cn.turboinfo.fuyang.api.entity.common.pojo.product.ProductSku;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class ProductSkuReviewUseCase extends AbstractUseCase<ProductSkuReviewUseCase.InputData, ProductSkuReviewUseCase.OutputData> {
    private final ProductService productService;
    private final ProductSkuService productSkuService;
    private final HousekeepingCompanyService housekeepingCompanyService;

    @Override
    protected OutputData doAction(InputData inputData) {
        val productSku = productSkuService.getById(inputData.id).orElse(new ProductSku());
        productSkuService.updateStatus(productSku.getId(), inputData.getStatus());
        val product = productService.getById(productSku.getProductId()).orElse(new Product());
        val productSkuStatusSet = productSkuService.findSkuByProductId(productSku.getProductId()).stream().map(ProductSku::getStatus).collect(Collectors.toSet());
        // 下架商品
        if(!productSkuStatusSet.contains(ProductSkuStatus.PUBLISHED)) {
            productService.updateStatus(productSku.getProductId(), ProductStatus.OFF_SHELF);
        } else {
            productService.updateStatus(productSku.getProductId(), ProductStatus.PUBLISHED);
        }
        //更新企业产品数量
        housekeepingCompanyService.updateProductNum(product.getCompanyId(), productService.countByCompanyId(product.getCompanyId()));
        return OutputData.builder()
                .build();
    }

    @EqualsAndHashCode(
            callSuper = true
    )
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {
        @NotNull(
                message = "编码不能为空"
        )
        private Long id;

        @NotNull(
                message = "状态不能为空"
        )
        private ProductSkuStatus status;
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
    }
}
